package com.cmcc.aregister.cs.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.cache.CacheManager;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.ui.activity.HaoyuanTipActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class HaoyuanTipService extends Service {

	public static final String ACTION = "com.cmcc.aregister.cs.service.HaoyuanTipService";
	private static final String TAG = "HaoyuanTipService";
	private Notification mNotification;
	private NotificationManager mManager;
	MyApplication app = MyApplication.getInstance();

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		initNotifiManager();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		new PollingThread().start();
	}

	// 初始化通知栏配置
	private void initNotifiManager() {
		mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		int icon = R.drawable.icon;
		mNotification = new Notification();
		mNotification.icon = icon;
		// mNotification.tickerText = "New Message";
		mNotification.defaults = Notification.DEFAULT_SOUND;
		mNotification.flags = Notification.FLAG_AUTO_CANCEL;
	}

	// 弹出Notification
	private void showNotification() {
		mNotification.when = System.currentTimeMillis();
		// Navigator to the new activity when click the notification title
		Intent i = new Intent(this, HaoyuanTipActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,
				Intent.FLAG_ACTIVITY_NEW_TASK);
		String[] contentVlues = getHaoyuanTipContent();
		if (contentVlues != null) {
			String content = "您好，" + contentVlues[2] + "医生在" + contentVlues[3]
					+ "小时后放号，点击查看！";
			mNotification.setLatestEventInfo(this,
					getResources().getString(R.string.p_haoyuan_tip), content,
					pendingIntent);
			mManager.notify(0, mNotification);
			// 提醒后，删除缓存
			CacheManager.getInstance().deleteHaoyuanTipCache(contentVlues[4]);
		}
	}

	/**
	 * 组装号源提醒内容
	 * 
	 * @return
	 */
	private String[] getHaoyuanTipContent() {
		String phone = ConfigUtilHelper.getMobile(app);
		Log.i(TAG, "当前登陆用户手机号码:" + phone);
		if (!"".equals(phone) && phone != null) {
			ArrayList<HashMap<String, String>> list = (ArrayList) CacheManager
					.getInstance().queryHaoyuanTipCache(phone);
			String startTime = "";
			String hosName = "";
			String depName = "";
			String docName = "";
			String id = "";
			String[] values = new String[5];
			int compareTime = 0;
			if (list != null && list.size() != 0) {
				for (HashMap<String, String> map : list) {
					startTime = (String) map.get("startTime");
					hosName = (String) map.get("hosName");
					depName = (String) map.get("depName");
					docName = (String) map.get("docName");
					id = (String) map.get("id");
					compareTime = getTime(startTime);
					// 24小时内
					if (compareTime != 0 && compareTime <= 24) {
						values[0] = hosName;
						values[1] = depName;
						values[2] = docName;
						values[3] = String.valueOf(compareTime);
						values[4] = id;
						return values;
					}
				}
			}
		}
		return null;
	}

	/**
	 * 获取时间
	 * 
	 * @param sdate
	 * @return
	 */
	public static int getTime(String sdate) {
		Date time = toDate(sdate);
		int hour = 0;
		Calendar cal = Calendar.getInstance();
		// 判断是否是同一天
		// String curDate = dateFormater2.get().format(cal.getTime());
		// String paramDate = dateFormater2.get().format(time);
		// if (curDate.equals(paramDate)) {
		hour = (int) ((time.getTime() - cal.getTimeInMillis()) / 3600000);
		return hour;
		// }
		// return hour;
	}

	/**
	 * 将字符串转位日期类型
	 * 
	 * @param sdate
	 * @return
	 */
	public static Date toDate(String sdate) {
		try {
			return dateFormater.get().parse(sdate);
		} catch (ParseException e) {
			return null;
		}
	}

	private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		}
	};

	private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
		@Override
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd");
		}
	};

	/**
	 * Polling thread 模拟向Server轮询的异步线程
	 * 
	 * @Author Ryan
	 * @Create 2013-7-13 上午10:18:34
	 */
	// int count = 0;

	class PollingThread extends Thread {
		@Override
		public void run() {
			// count++;
			// 当计数能被5整除时弹出通知
			// if (count % 5 == 0) {
			showNotification();
			// }
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		System.out.println("Service:onDestroy");
	}

}
